package com.leigang.swagger.config;

import com.google.common.collect.Maps;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * @author leigang
 * @description: 动态数据源核心配置文件
 * @date 20/8/12  21:59
 */
@Configuration
public class DataSourceConfig {
    @Resource
    Environment environment;

    @Bean
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        dynamicDataSource.setDefaultTargetDataSource(getDefaultDataSource());
        dynamicDataSource.setTargetDataSources(getDataSourceMap());

        return dynamicDataSource;
    }


    private Object getDefaultDataSource() {

        return DataSourceBuilder.create().driverClassName(DataSourceTypeConstant.DRIVER)
                .password(environment.getProperty(String.format(DataSourceTypeConstant.DEFAULT_ENV_NAME, DataSourceTypeConstant.PASSWORD)))
                .url(environment.getProperty(String.format(DataSourceTypeConstant.DEFAULT_ENV_NAME, DataSourceTypeConstant.URL)))
                .username(environment.getProperty(String.format(DataSourceTypeConstant.DEFAULT_ENV_NAME, DataSourceTypeConstant.USERNAME))).build();
    }

    private Map<Object, Object> getDataSourceMap() {
        Map<Object, Object> dataSourceMap = Maps.newHashMap();

        List<String> allDatasource = DataSourceTypeConstant.ALL_DATASOURCE;

        DataSourceBuilder<?> sourceBuilder = DataSourceBuilder.create().driverClassName(DataSourceTypeConstant.DRIVER);

        for (String name : allDatasource) {
            DataSource dataSource = sourceBuilder.password(environment.getProperty(String.format(DataSourceTypeConstant.ENV_NAME, name, DataSourceTypeConstant.PASSWORD)))
                    .url(environment.getProperty(String.format(DataSourceTypeConstant.ENV_NAME, name, DataSourceTypeConstant.URL)))
                    .username(environment.getProperty(String.format(DataSourceTypeConstant.ENV_NAME, name, DataSourceTypeConstant.USERNAME))).build();
            dataSourceMap.put(name, dataSource);
        }
        return dataSourceMap;
    }
}
